const { query } = require('express')
const dataBase = require('../dataBase')

// 添加二手物品
function addUsedGoodsInfo(req, res){
    const newUsedGoodsInfo = req.body

    const addUsedGoodsInfoSql = 'insert into usedgoods(uId, articlesName, articlesInfo, articlesOriginalPrice, articlesSecondHandPrice, articlesType, articlesReleaseTime, articlesImgSrcs) VALUE (?, ?, ?, ?, ?, ?, ?, ?)'

    dataBase.query(addUsedGoodsInfoSql, [newUsedGoodsInfo.uId, newUsedGoodsInfo.articlesName, newUsedGoodsInfo.articlesInfo, newUsedGoodsInfo.articlesOriginalPrice, newUsedGoodsInfo.articlesSecondHandPrice, newUsedGoodsInfo.articlesType, newUsedGoodsInfo.articlesReleaseTime, newUsedGoodsInfo.articlesImgSrcs], (err, results) => {
        if(err){
            return res.ErrorFun('未知错误！请稍后重试！')
        }

        if(results.affectedRows !== 1){
            return res.ErrorFun('添加失败！')
        }

        res.send({
            status: 200,
            message: '添加成功！',
        })
    })
}

// 获取所有二手物品（默认按上传时间降序）
function getUsedGoodsInfos(req, res){
    const size = req.query.size
    let last = 20 * size

    const getUsedGoodsInfosSql = 'select * from usedgoods order by articlesReleaseTime DESC limit  0, ?'

    dataBase.query(getUsedGoodsInfosSql, last, (err, results) => {
        if(err){
            return res.ErrorFun('未知错误！请稍后重试！')
        }

        res.send({
            status: 200,
            message: '获取成功！',
            usedGoodsInfos: results
        })
    })
}


// 获取分类二手物品
function getClassificationUsedGoodsInfos(req, res){

    const size = req.query.size
    let last = 20 * size

    const getClassificationUsedGoodsInfosSql = 'select * from usedgoods where articlesType = ? order by articlesReleaseTime DESC limit  0, ?'

    dataBase.query(getClassificationUsedGoodsInfosSql, [req.query.articlesType, last], (err, results) => {
        if(err){
            return res.ErrorFun('未知错误！请稍后重试！')
        }

        res.send({
            status: 200,
            message: '获取成功！',
            classificationUsedGoodsInfos: results
        })
    })
}

// 获取卖家联系方式及其所在高校学院昵称
function getSellerInfo(req, res){

    const seller = req.query.uId

    const getSellerInfoSql = 'select phoneNumber, QQMail, nickname, university, college from personalinformation where id = ?'

    dataBase.query(getSellerInfoSql, seller, (err, results) => {
        if(err){
            return res.ErrorFun('未知错误！稍后再试！')
        }

        res.send({
            status: 200,
            message: '获取成功！',
            sellerInfo: results[0]
        })
    })
}

module.exports = {
    addUsedGoodsInfo,
    getUsedGoodsInfos,
    getClassificationUsedGoodsInfos,
    getSellerInfo
}